package com.yyl.rbacs.utils;

import com.yyl.rbacs.exception.IllegalCharacterException;
import org.springframework.util.StringUtils;
/**
 * @BelongsProject: rbacs
 * @BelongsPackage: com.yyl.rbacs.utils
 * @Author: YuanSir
 * @CreateTime: 2022-11-01  10:28
 * @Description:
 * @Version: 1.0
 */

public class SQLFilter {
    
    /**
     * SQL注入过滤
     * @param str  待验证的字符串
     */
    public static String sqlInject(String str){
        if(str == null || "".equals(str)){
            return null;
        }
        //去掉'|"|;|\字符
        str = StringUtils.replace(str, "'", "");
        str = StringUtils.replace(str, "\"", "");
        str = StringUtils.replace(str, ";", "");
        str = StringUtils.replace(str, "\\", "");
        
        //转换成小写
        str = str.toLowerCase();
        
        //非法字符
        String[] keywords = {"master", "truncate", "insert", "select", "delete", "update", "declare", "alter", "drop"};
        
        //判断是否包含非法字符
        for(String keyword : keywords){
            if(str.indexOf(keyword) != -1){
                throw new IllegalCharacterException("包含非法字符");
            }
        }
        
        return str;
    }
    
}
